package com.xuxu.controller;

import com.xuxu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/users")
public class UserController {

    //注入 RestTemplate http客户端
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/findById/{id}")
    public User findById(@PathVariable Long id){

        //根据服务名称获取服务实例
        ServiceInstance serviceInstance = discoveryClient.getInstances("user_service").get(0);
        //获取地址
        String host = serviceInstance.getHost();
        //获取端口号
        int port = serviceInstance.getPort();

        //拼接url
        String url = "http://"+host+":"+port+"/user/"+id;

        //使用http客户端 restTemplate访问 url
        return restTemplate.getForObject(url,User.class);

    }
}
